package com.ugoodtech.mdcc.web.service.impl;

import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.ImportStationService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class ImportStationServiceImpl implements ImportStationService {

    private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";

    /**
     * 判断Excel的版本,获取Workbook
     *
     * @param in
     * @return
     * @throws IOException
     */
    private static Workbook getWorkbok(InputStream in, File file) throws IOException {
        Workbook wb = null;
        if (file.getName().endsWith(EXCEL_XLS)) {
            //Excel 2003
            wb = new HSSFWorkbook(in);
        } else if (file.getName().endsWith(EXCEL_XLSX)) {
            // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }

    /**
     * 判断文件是否是excel
     *
     * @throws Exception
     */
    private static JsonResponse checkExcelVaild(File file) {
        if (!file.exists()) {
            return JsonResponse.errorResponseWithError("抱歉", "文件不存在");
        }
        if (!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))) {
            return JsonResponse.errorResponseWithError("抱歉", "文件不是Excel");
        }
        return JsonResponse.successResponse();
    }


    public void readExcel(String fileName) throws Exception {
        // 同时支持Excel 2003、2007
        // 创建文件对象
        File excelFile = new File(fileName);
        // 文件流
        FileInputStream in = new FileInputStream(excelFile);
        if (!checkExcelVaild(excelFile).isSuccess()) {
            return;
        }
        Workbook workbook = getWorkbok(in, excelFile);
        // 这种方式 Excel2003/2007/2010都是可以处理的
        //Workbook workbook = WorkbookFactory.create(is);

        //获取第一个sheet
        //为跳过第一行标题设置
        int count = 0;
        Sheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            if (count < 1) {
                continue;
            }

        }


    }


}
